package net.vonkannen.callduration;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.CallLog;
import android.text.format.Time;

public class UserPresentService extends Service {
	private static final String PREFS_NAME = "CallDuration_prefs";

	@Override
	public IBinder onBind(Intent arg0) {

		return null;
	}
	
    Calendar durationCalendar = Calendar.getInstance();
    SimpleDateFormat durationFormat = new SimpleDateFormat("KK:mm:ss");
	@Override
	public void onStart(Intent intent, int startid) {	/* Called when keyguard is gone */
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		if((settings.getBoolean("ShowLastCall", false)) && !(settings.getBoolean("newCall", true))) {
			//Log.v("DebugTag", "Display got unlocked and it has not seen call durations!");
			Time timer = new Time();	/* Set time when unlocked */
			timer.setToNow();
			if(timer.toMillis(true)-settings.getLong("LastCallTime", 0)<=30000) {
				//Log.v("DebugTag", "You're lucky! Right in time, so you can see your last call duration! Congratulations!");

				/* Set up time formatter */
				durationCalendar.setTimeZone(TimeZone.getTimeZone("UTF"));
				durationFormat.setTimeZone(durationCalendar.getTimeZone());
				
				/* Set up cursor to read out duration */
				Cursor c = getContentResolver().query(
			               android.provider.CallLog.Calls.CONTENT_URI,
			               null,
			               null,
			               null,
			               android.provider.CallLog.Calls.DATE + " DESC");
				c.moveToFirst();
				long duration = c.getLong(c.getColumnIndex(CallLog.Calls.DURATION));
				
				/* Create output for toast */
				durationCalendar.setTimeInMillis(duration*1000);
				String durationOutput = getString(R.string.duration) + " " + durationFormat.format(durationCalendar.getTime());
				
		        /* Create and show toast */
				CustomToast toast = new CustomToast(getApplicationContext(),
						durationOutput,
						Integer.parseInt(settings.getString("radius", "4").toString()),
						Integer.parseInt(settings.getString("borderthickness", "6").toString()),
						(int) Long.parseLong(settings.getString("bordercolor", "FFABABAB").toString(), 16),
						(int) Long.parseLong(settings.getString("bgcolor", "FA444444").toString(), 16),
						(int) Long.parseLong(settings.getString("fontcolor", "FFFFFFFF").toString(), 16),
						settings.getBoolean("showicon", true));
				toast.show();
			}
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("ShowLastCall", false);
			editor.putBoolean("newCall", true);
			editor.commit();
		}
		
		Intent stop = new Intent("net.vonkannen.callduration.UserPresentService");
		this.stopService(stop);
	}

}
